package com.jsu.springboot_crop.controller;

import com.jsu.springboot_crop.common.Result;
import com.jsu.springboot_crop.common.StatusCode;
import com.jsu.springboot_crop.entity.Reserve;
import com.jsu.springboot_crop.service.ReserveService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/reserve")
public class ReserveController {
    @Autowired
   private ReserveService reserveService;
    @PostMapping("/add")
    public Result add(@RequestBody Reserve reserve, BindingResult bindingResult){
        //检查项目
        if (bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String fail = stringBuffer.toString();
            System.out.println(fail);
            return new Result<String>(false, StatusCode.ERROR, "添加失败",fail);
        }
        reserveService.insert(reserve);
        return new Result(true, StatusCode.OK, "添加成功");
    }


    //查询个人预约
    @GetMapping("/selectByKind/{kind}")
    public Result selectByKind(@PathVariable("kind")String kind){
        List<Reserve> reserves = reserveService.selectByReserve(kind);
        return new Result(true, StatusCode.OK,"查询成功",reserves);
    }
    //根据id修改预约
    @PutMapping("/update")
    public Result update(@RequestBody Reserve reserve, BindingResult bindingResult){
        reserveService.updateById(reserve);
        return new Result(true,StatusCode.OK,"修改成功",null);
    }
    //根据id删除预约
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id")Integer id){
        reserveService.delete(id);
        return new Result(true,StatusCode.OK,"删除成功",null);
    }
    //根据id查询预约
    @GetMapping("/selectId/{id}")
    public Result selectById(@PathVariable("id") Integer id){
        Reserve reserve = reserveService.selectById(id);
        return new Result(true,StatusCode.OK,"查询成功",reserve);
    }
}
